# -*- coding = utf-8 -*-
# name   : 
# Author : admin
# Email  : 
# File   : operate_mongodb.py.py
# Ver    : 1.0
# Time   : 2025-07-15 09:22

import logging
import pymongo

from config import MONGODB_CONF




class OperateMongodb:
    """
    普通模式 MongoDB 连接类（每次新建连接）
    """

    def __init__(self, config=MONGODB_CONF):
        self.host = config.get("HOST")
        self.port = config.get("PORT")
        self.username = config.get("USERNAME")
        self.password = config.get("PASSWORD")
        self.auth_source = config.get("DEFAULT_DB")
        self.db_name = config.get("DEFAULT_DB")
        self.max_pool_size = config.get("MAX_POOL_SIZE", 100)

        self.client = self._create_client()
        self.db = self.client[self.db_name]

        self.client.admin.command('ping')
        logging.info(f"普通模式，登录成功，use：{config.get('DEFAULT_DB')}")

    def _create_client(self):
        """创建带认证的 MongoDB 客户端"""
        uri = f"mongodb://{self.username}:{self.password}@{self.host}:{self.port}/{self.db_name}"
        uri += f"?authSource={self.auth_source}&maxPoolSize={self.max_pool_size}"
        return pymongo.MongoClient(uri)

    def close(self):
        """关闭当前连接"""
        if self.client:
            self.client.close()

    def get_db(self):
        """获取数据库对象"""
        return self.db

    def conn_mongodb(self):
        """连接数据库"""
        self.client = self._create_client()
        self.db = self.client[self.db_name]
        return self.client, self.db
